<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-input class="cd-mb8" v-model="filterText" placeholder="请输入" clearable size="small"
            prefix-icon="el-icon-search" />
          <el-tree class="input-tree" :data="treeList" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
            node-key="id" highlight-current @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="清单编号" prop="manifestCode">
              <el-input v-model="queryParams.manifestCode" placeholder="请输入清单编号" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="清单名称" prop="manifestName">
              <el-input v-model="queryParams.manifestName" placeholder="请输入清单名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
            <el-row v-if="treeInfo && treeInfo.type == 'supplier'" :gutter="10"
              class="mb8 cd-pr8 top-right-btn small-line-height">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                  v-hasPermi="['ma:materialManifest:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-if="canUpdate" type="success" plain icon="el-icon-edit" size="mini"
                  :loading="buttonLoading" @click="submitForm" v-hasPermi="['ma:materialManifest:edit']">保存</el-button>
                <el-button v-else type="primary" plain icon="el-icon-edit" size="mini" @click="onUpdate"
                  v-hasPermi="['ma:materialManifest:edit']">编辑</el-button>
              </el-col>
              <!-- <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['ma:materialManifest:edit']">修改</el-button>
            </el-col> -->
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                  @click="handleDelete" v-hasPermi="['ma:materialManifest:remove']">删除</el-button>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                  v-hasPermi="['ma:materialManifest:importData']">导入</el-button>
              </el-col> -->
              <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
            </el-row>
          </el-form>

          <el-table border stripe v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="清单编号" align="center" prop="manifestCode" min-width="120" show-overflow-tooltip />
            <el-table-column label="清单名称" align="center" prop="manifestName" min-width="140" show-overflow-tooltip />
            <el-table-column label="型号" align="center" prop="model" min-width="80" show-overflow-tooltip />
            <el-table-column label="规格" align="center" prop="specification" min-width="80" show-overflow-tooltip />
            <el-table-column label="单位" align="center" prop="unit" min-width="80" show-overflow-tooltip />
            <el-table-column label="数量" header-align="center" align="right" prop="manifestNumber" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input v-if="canUpdate" size="mini" type="number" v-model="scope.row.manifestNumber"
                  @change="computeManifestTotal(scope.row)" />
                <span v-else>{{ scope.row.manifestNumber }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单价" header-align="center" align="right" prop="manifestPrice" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input v-if="canUpdate" size="mini" type="number" v-model="scope.row.manifestPrice"
                  @change="computeManifestTotal(scope.row)" />
                <span v-else>{{ scope.row.manifestPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="金额" header-align="center" align="right" prop="manifestTotal" min-width="120"
              show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.manifestTotal }}
              </template>
            </el-table-column>
            <el-table-column label="调整额" align="center" prop="adjustments" min-width="120">
              <template slot-scope="scope">
                <el-input v-if="canUpdate" size="mini" type="number" v-model="scope.row.adjustments" />
                <span v-else>{{ scope.row.adjustments }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['ma:materialManifest:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['ma:materialManifest:remove']">删除</el-button>
              </template>
</el-table-column> -->
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />


        </div>
      </el-col>
    </el-row>
    <standard-manifest-select ref="standardManifestSelect" @callBack="setDetailList" />
  </div>
</template>

<script>
import { querySupplierTreeList } from "@/api/base/bsBd";
import { listMaterialManifest, delMaterialManifest, addListMaterialManifest, updateListMaterialManifest } from "@/api/ma/materialManifest";
import { mapGetters } from "vuex";
import standardManifestSelect from '../standardManifest/standardManifestSelect.vue';
import decimal from "@/utils/big-decimal";

export default {
  components: { standardManifestSelect },
  dicts: ["material_manifest_type"],

  name: "MaterialManifest",
  data () {
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      filterText: undefined,
      canUpdate: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料清单表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bdId: undefined,
        zdId: undefined,
        gysId: undefined,
        type: undefined,
        manifestCode: undefined,
        manifestName: undefined,
        model: undefined,
        specification: undefined,
        unit: undefined,
        manifestNumber: undefined,
        manifestPrice: undefined,
        manifestTotal: undefined,
        adjustments: undefined,
      },
      projectId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // manifestId: [
        //   { required: true, message: "清单id不能为空", trigger: "blur" }
        // ],
        // bdId: [
        //   { required: true, message: "标段id不能为空", trigger: "blur" }
        // ],
        // gysId: [
        //   { required: true, message: "供应商id不能为空", trigger: "blur" }
        // ],
        // type: [
        //   { required: true, message: "类型id不能为空", trigger: "change" }
        // ],
        manifestCode: [
          { required: true, message: "清单编号不能为空", trigger: "blur" }
        ],
        manifestName: [
          { required: true, message: "清单名称不能为空", trigger: "blur" }
        ],
        // model: [
        //   { required: true, message: "型号不能为空", trigger: "blur" }
        // ],
        // specification: [
        //   { required: true, message: "规格不能为空", trigger: "blur" }
        // ],
        // unit: [
        //   { required: true, message: "单位不能为空", trigger: "blur" }
        // ],
        // manifestNumber: [
        //   { required: true, message: "清单数量不能为空", trigger: "blur" }
        // ],
        // manifestPrice: [
        //   { required: true, message: "清单单价不能为空", trigger: "blur" }
        // ],
        // manifestTotal: [
        //   { required: true, message: "清单金额不能为空", trigger: "blur" }
        // ],
        // adjustments: [
        //   { required: true, message: "调整额不能为空", trigger: "blur" }
        // ],
      },
    };
  },
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    },
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.getBdTree();
    },
    getBdTree () {
      querySupplierTreeList({ projectId: this.projectId }).then((response) => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            // this.$refs.tree.setCurrentKey(this.treeList[0].id);
            // this.handleNodeClick(this.treeList[0]);
          } else {
            this.treeInfo = {};
            this.queryParams.bdId = null;
            this.queryParams.zdId = null;
            this.dataList = [];
            this.total = 0;
          }
        });
      });
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick (data) {
      this.treeInfo = data;
      if (data.type == "supplier") {
        this.queryParams.zdId = data.parentId; // 站点ID
        this.queryParams.gysId = data.id; // 供应商ID
        this.handleQuery();
      } else {
        // this.$message.warning('请选择供应商！');
      }
    },
    /** 查询材料清单列表 */
    getList () {
      this.loading = true;
      listMaterialManifest(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.canUpdate = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        manifestId: undefined,
        bdId: undefined,
        gysId: this.treeInfo.id,
        gysName: this.treeInfo.label,
        type: undefined,
        manifestCode: undefined,
        manifestName: undefined,
        model: undefined,
        specification: undefined,
        unit: undefined,
        manifestNumber: undefined,
        manifestPrice: undefined,
        manifestTotal: undefined,
        adjustments: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.manifestId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.$refs.standardManifestSelect.init(this.treeInfo.value, this.dataList);
    },
    // 新增保存
    setDetailList (list) {

      // 保存
      this.submitForm(list);
    },
    /** 编辑按钮操作 */
    onUpdate () {
      this.canUpdate = true;
    },
    // 计算合计金额
    computeManifestTotal (row) {
      let a = row.manifestNumber; //数量
      let b = row.manifestPrice; //单价
      if (a && b) {
        row.manifestTotal = decimal.multiply(a, b);
      } else {
        row.manifestTotal = 0;
      }
    },
    /** 提交按钮 */
    submitForm (list) {
      this.buttonLoading = true;
      if (list && list.length > 0) {
        const info = {
          gysId: this.treeInfo.id,
          addList: list
        };
        // 保存
        addListMaterialManifest(info).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        });
      } else {
        const info = {
          gysId: this.treeInfo.id,
          updateList: this.dataList
        };
        updateListMaterialManifest(info).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const manifestIds = row.manifestId || this.ids;
      let title = '是否确认删除选中的数据项？';
      if (row.manifestId) {
        title = `是否确认删除材料清单编号为${row.manifestCode}的数据项？`;
      }
      this.$modal.confirm(title).then(() => {
        this.loading = true;
        return delMaterialManifest(manifestIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "甲供材料清单导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download('ma/materialManifest/importTemplate', {
      }, `材料清单导入模板_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    },
  }
};
</script>
